package cn.tedu._10article.base.exception;

import cn.tedu._10article.base.response.Result;
import cn.tedu._10article.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        String message = exception.getFieldError().getDefaultMessage();
        log.debug("全局异常处理器handleMethodArgumentNotValidException执行了：" + message);
        return Result.fail(StatusCode.VALIDATED_ERROR, message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleConstraintViolationException(ConstraintViolationException exception) {
        String message = exception.getMessage();
        log.debug("全局异常处理器handleConstraintViolationException执行了：" + message);
        return Result.fail(StatusCode.VALIDATED_ERROR, message);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result handleMaxUploadSizeExceededException(MaxUploadSizeExceededException exception) {
        String message = exception.getMessage();
        log.debug("全局异常处理器MaxUploadSizeExceededException执行了：" + message);
        return Result.fail(StatusCode.VALIDATED_ERROR, message);
    }
}
